package com.jhgsys.internal.formDesign.service.impl;

import com.jhgsys.internal.contractor.dto.BaseContractorTeamDto;
import com.jhgsys.internal.contractor.entity.BaseContractorTeam;
import com.jhgsys.internal.formDesign.dto.FormDesignDto;
import com.jhgsys.internal.formDesign.entity.FormDesign;
import com.jhgsys.internal.formDesign.entity.FormFill;
import com.jhgsys.internal.formDesign.entity.FormPublishObject;
import com.jhgsys.internal.formDesign.mapper.FormDesignMapper;
import com.jhgsys.internal.formDesign.service.IFormDesignService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.formDesign.service.IFormPublishObjectService;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 表单设计 Service实现
 *
 * @author fenghaijun
 * @date 2024-08-28 10:54:00
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FormDesignServiceImpl extends ServiceImpl<FormDesignMapper, FormDesign> implements IFormDesignService {

    @Autowired
    private IFormPublishObjectService formPublishObjectService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private ITenantService tenantService;

    /**
     * 查询（分页）
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     * @param request QueryRequest
     * @param formDesignDto formDesign
     * @return IPage<FormDesign>
    */
    @Override
    public IPage<FormDesignDto> findFormDesignPage(QueryRequest request, FormDesignDto formDesignDto) {
        LambdaQueryWrapper<FormDesign> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FormDesign::getDeletedFlg, 0);

        queryWrapper.eq(FormDesign::getTenantId, formDesignDto.getTenantId());
        if(StringUtils.isNotBlank(formDesignDto.getTemplateFlg())){
            queryWrapper.eq(FormDesign::getTemplateFlg, formDesignDto.getTemplateFlg());
        }
        if(StringUtils.isNotBlank(formDesignDto.getFormName())){
            queryWrapper.like(FormDesign::getFormName, formDesignDto.getFormName());
        }
        if(ObjectUtils.isNotEmpty(formDesignDto.getStartDate())){
            queryWrapper.le(FormDesign::getStartDate, formDesignDto.getStartDate());
        }
        if(ObjectUtils.isNotEmpty(formDesignDto.getEndDate())){
            queryWrapper.ge(FormDesign::getEndDate, formDesignDto.getEndDate());
        }
        if(StringUtils.isNotBlank(formDesignDto.getStatus())){
            queryWrapper.eq(FormDesign::getStatus, formDesignDto.getStatus());
        }
        queryWrapper.orderByDesc(FormDesign::getCreatedTime);
        Page<FormDesign> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<FormDesign> pageResult= this.page(page, queryWrapper);
        List<FormDesign> formDesignList = pageResult.getRecords();

        IPage<FormDesignDto> dtoPageList = new Page<>();
        dtoPageList.setTotal(pageResult.getTotal());
        dtoPageList.setCurrent(pageResult.getCurrent());
//        查FormPublishObject表赋值适用部门/适用人
        if(!CollectionUtils.isEmpty(formDesignList)) {
            List<FormDesignDto> formDesignDtoList = new ArrayList<>();
            for (FormDesign formDesignItem : formDesignList) {
                FormDesignDto formDesignDtoObj = new FormDesignDto();
                BeanUtils.copyProperties(formDesignItem, formDesignDtoObj);

                FormPublishObject publishObjectParam = new FormPublishObject();
                publishObjectParam.setTenantId(formDesignItem.getTenantId());
                publishObjectParam.setDesignId(formDesignItem.getDesignId());
                List<FormPublishObject> formPublishObjectList = formPublishObjectService.findFormPublishObjectList(publishObjectParam);
                List<String> collect = formPublishObjectList.stream().map(FormPublishObject::getObjectId).collect(Collectors.toList());
                if ("2".equals(formDesignItem.getPublishObject())) {
                    List<Dept> deptList = deptService.findDeptByDeptIds(collect);
                    formDesignDtoObj.setDeptList(deptList);

                } else if ("3".equals(formDesignItem.getPublishObject())) {
                    List<User> userList = userService.findUserByUserIds(collect);
                    formDesignDtoObj.setUserList(userList);
                }
//                公司名称赋值
                Tenant tenant = tenantService.findTenantByTenantId(formDesignItem.getTenantId());
                formDesignDtoObj.setTenantName(Optional.ofNullable(tenant).map(Tenant::getTenantName).orElse(""));
                formDesignDtoList.add(formDesignDtoObj);
            }
            dtoPageList.setRecords(formDesignDtoList);
        }
        return dtoPageList;
    }

    @Override
    public IPage<FormDesignDto> findFormFillPage(QueryRequest request, FormDesignDto formDesignDto) {
        Page<FormDesignDto> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        IPage<FormDesignDto>  pageinfo = this.baseMapper.selectFormDesignPage(page,formDesignDto);
        return pageinfo;
    }
    /**
     * 查询（所有）
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     * @param formDesign formDesign
     * @return List<FormDesign>
     */
    @Override
    public List<FormDesign> findFormDesignList(FormDesign formDesign) {
	    LambdaQueryWrapper<FormDesign> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FormDesign::getDeletedFlg, 0);
		// TODO 设置查询条件
        if(StringUtils.isNotBlank(formDesign.getTenantId())){
            queryWrapper.eq(FormDesign::getTenantId, formDesign.getTenantId());
        }
        if(StringUtils.isNotBlank(formDesign.getTemplateFlg())){
            queryWrapper.eq(FormDesign::getTemplateFlg, formDesign.getTemplateFlg());
        }
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author fenghaijun
    * @date 2024-08-28 10:54:00
    * @param id
    * @return FormDesign
    */
    @Override
    public FormDesignDto findFormDesignById(String id){
        FormDesignDto formDesignDto = new FormDesignDto();
        FormDesign formDesign = this.baseMapper.selectById(id);
        BeanUtils.copyProperties(formDesign,formDesignDto);
        if(null != formDesign){
            FormPublishObject publishObjectParam = new FormPublishObject();
            publishObjectParam.setTenantId(formDesign.getTenantId());
            publishObjectParam.setDesignId(formDesign.getDesignId());
            List<FormPublishObject> formPublishObjectList= formPublishObjectService.findFormPublishObjectList(publishObjectParam);
            List<String> collect = formPublishObjectList.stream().map(FormPublishObject::getObjectId).collect(Collectors.toList());
            if("2".equals(formDesign.getPublishObject())){
                List<Dept> deptList = deptService.findDeptByDeptIds(collect);
                formDesignDto.setDeptList(deptList);

            }else if("3".equals(formDesign.getPublishObject())){
                List<User> userList = userService.findUserByUserIds(collect);
                formDesignDto.setUserList(userList);
            }
            formDesignDto.setFormPublishObjectList(formPublishObjectList);
        }

        return formDesignDto;
    }

    /**
     * 新增
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     * @param formDesignDto formDesign
     */
    @Override
    @Transactional
    public void createFormDesign(FormDesignDto formDesignDto) {
//        存主表
        FormDesign formDesign = new FormDesign();
        BeanUtils.copyProperties(formDesignDto,formDesign);
        formDesign.setCreatedTime(new Date());
        this.save(formDesignDto);
//        存form_publish_object表

        if("2".equals(formDesignDto.getPublishObject())){
//            部门
            List<Dept> deptList = formDesignDto.getDeptList();
            for(Dept deptOne : deptList){
                FormPublishObject formPublishObject = new FormPublishObject();
                formPublishObject.setTenantId(formDesignDto.getTenantId());
                formPublishObject.setDesignId(formDesignDto.getDesignId());
                formPublishObject.setObjectId(deptOne.getDeptId());
                formPublishObject.setCreatedTime(new Date());
                formPublishObject.setCreatedBy(formDesignDto.getCreatedBy());
                formPublishObjectService.save(formPublishObject);
            }
        }else if("3".equals(formDesignDto.getPublishObject())){
//            个人
            List<User> userList = formDesignDto.getUserList();
            for(User userOne: userList){
                FormPublishObject formPublishObject = new FormPublishObject();
                formPublishObject.setTenantId(formDesignDto.getTenantId());
                formPublishObject.setDesignId(formDesignDto.getDesignId());
                formPublishObject.setObjectId(userOne.getUserId());
                formPublishObject.setCreatedTime(new Date());
                formPublishObject.setCreatedBy(formDesignDto.getCreatedBy());
                formPublishObjectService.save(formPublishObject);
            }
        }
    }


    /**
     * 修改
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     * @param formDesignDto formDesign
     */
    @Override
    @Transactional
    public void updateFormDesign(FormDesignDto formDesignDto) {
        formDesignDto.setUpdatedTime(new Date());
//        更新主表
        this.saveOrUpdate(formDesignDto);
//        更新form_publish_object表,先删除之前存在的数据
        if(!CollectionUtils.isEmpty(formDesignDto.getFormPublishObjectList())){
            for(FormPublishObject formPublishObject:formDesignDto.getFormPublishObjectList()){
                formPublishObject.setDeletedFlg("1");
                formPublishObject.setDeletedBy(formDesignDto.getUpdatedBy());
                formPublishObjectService.saveOrUpdate(formPublishObject);
            }
        }
        if("2".equals(formDesignDto.getPublishObject())){
            List<Dept> deptList = formDesignDto.getDeptList();
            for(Dept deptOne : deptList){
                FormPublishObject formPublishObject = new FormPublishObject();
                formPublishObject.setTenantId(formDesignDto.getTenantId());
                formPublishObject.setDesignId(formDesignDto.getDesignId());
                formPublishObject.setObjectId(deptOne.getDeptId());
                formPublishObject.setCreatedTime(new Date());
                formPublishObject.setCreatedBy(formDesignDto.getCreatedBy());
                formPublishObjectService.saveOrUpdate(formPublishObject);
            }
        }else if("3".equals(formDesignDto.getPublishObject())){
            //            个人
            List<User> userList = formDesignDto.getUserList();
            for(User userOne: userList){
                FormPublishObject formPublishObject = new FormPublishObject();
                formPublishObject.setTenantId(formDesignDto.getTenantId());
                formPublishObject.setDesignId(formDesignDto.getDesignId());
                formPublishObject.setObjectId(userOne.getUserId());
                formPublishObject.setCreatedTime(new Date());
                formPublishObject.setCreatedBy(formDesignDto.getCreatedBy());
                formPublishObjectService.saveOrUpdate(formPublishObject);
            }
        }
    }

    /**
     * 逻辑删除
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     * @param formDesign formDesign
     * @param formDesignIds formDesignIds
     */
    @Override
    @Transactional
    public void deleteFormDesign(FormDesign formDesign,String formDesignIds) {
        List<String> list = Arrays.asList(formDesignIds.split(StringPool.COMMA));
        this.baseMapper.update(formDesign,new LambdaQueryWrapper<FormDesign>().in(FormDesign::getDesignId,list));
	}

    /**
    * 物理删除
    * @author fenghaijun
    * @date 2024-08-28 10:54:00
    * @param formDesignIds formDesignIds
    */
    @Override
    @Transactional
    public void physicallyDeleteFormDesign(String formDesignIds) {
        List<String> list = Arrays.asList(formDesignIds.split(StringPool.COMMA));
        LambdaQueryWrapper<FormDesign> wapper = new LambdaQueryWrapper<>();
        wapper.in(FormDesign::getDesignId,list);
        this.remove(wapper);
    }
}
